<script setup>
import { ref, onMounted, computed } from 'vue'
import api from '@/utils/api'
import Toast from '@/components/Toast.vue'
import { showToast } from '@/utils/toast'
import draggable from 'vuedraggable'  // 需要安装: npm install vuedraggable@next

// 预算列表数据
const budgets = ref([]) // 存储预算列表数据
const loading = ref(false) // 加载状态标识

// 添加和更新预算弹窗相关状态
const showAddModal = ref(false) // 控制添加预算弹窗显示
const showEditModal = ref(false) // 控制编辑预算弹窗显示
const currentBudget = ref(null) // 当前正在编辑的预算对象

// 新预算表单数据对象
const newBudget = ref({
  category: '', // 预算类型
  amount: '', // 预算金额
  description: '' // 备注说明
})

// 预算类型选项列表
const budgetCategories = [
  { value: '房租', label: '房租' },
  { value: '交通', label: '交通' },
  { value: '伙食', label: '伙食' },
  { value: '购物', label: '购物' },
  { value: '娱乐', label: '娱乐' },
  { value: '教育', label: '教育' },
  { value: '医疗', label: '医疗' },
  { value: '其他', label: '其他' }
]

// 计算总预算金额
const totalBudget = computed(() => budgets.value.reduce((sum, budget) => sum + budget.amount, 0))

// 计算实际总支出金额
const totalActualExpense = computed(() => budgets.value.reduce((sum, budget) => sum + (budget.actual_expense || 0), 0))

// 根据实际支出是否超出预算计算显示颜色
const actualExpenseColor = computed(() => {
  return totalActualExpense.value > totalBudget.value ? '#f56c6c' : '#67c23a'
})

// 获取预算列表数据
const getBudgets = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/get_budgets')
    if (response.data.code === 0) {
      budgets.value = response.data.data || []
    }
  } catch (error) {
    showToast('获取预算列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 验证表单数据是否合法
const validateForm = () => {
  if (!newBudget.value.category) {
    showToast('请选择预算类型', 'error')
    return false
  }
  
  if (!newBudget.value.amount || parseFloat(newBudget.value.amount) <= 0) {
    showToast('请输入有效的金额', 'error')
    return false
  }
  
  return true
}

// 重置预算表单数据
const resetForm = () => {
  newBudget.value = {
    category: '',
    amount: '',
    description: ''
  }
}

// 添加新预算
const handleAddBudget = async () => {
  if (!validateForm()) {
    return
  }

  try {
    const response = await api.post('/api/add_budget', newBudget.value)
    if (response.data.code === 0) {
      showToast('添加成功', 'success')
      showAddModal.value = false
      await getBudgets()
      resetForm()
    } else {
      showToast(response.data.message, 'error')
    }
  } catch (error) {
    showToast('添加失败', 'error')
  }
}

// 更新预算信息
const handleUpdateBudget = async () => {
  if (!validateForm()) {
    return
  }

  try {
    const response = await api.put('/api/update_budget', {
      budget_id: currentBudget.value.id,
      category: newBudget.value.category,
      amount: newBudget.value.amount,
      description: newBudget.value.description
    })
    
    if (response.data.code === 0) {
      showToast('更新成功', 'success')
      showEditModal.value = false
      await getBudgets()
      resetForm()
    } else {
      showToast(response.data.message, 'error')
    }
  } catch (error) {
    showToast('更新失败', 'error')
  }
}

// 删除预算
const handleDeleteBudget = async (id) => {
  if (confirm('确定要删除这条预算吗？')) {
    try {
      const response = await api.delete('/api/delete_budget', { 
        data: { budget_id: id }
      })
      if (response.data.code === 0) {
        showToast('删除成功', 'success')
        await getBudgets()
      } else {
        showToast(response.data.message, 'error')
      }
    } catch (error) {
      showToast('删除失败', 'error')
    }
  }
}

// 格式化金额显示
const formatAmount = (amount) => {
  return amount.toFixed(2)
}

// 根据预算类型值获取对应的显示标签
const getCategoryLabel = (value) => {
  const category = budgetCategories.find(item => item.value === value)
  return category ? category.label : value
}

// 打开编辑预算弹窗
const openEditModal = (budget) => {
  currentBudget.value = budget
  newBudget.value = {
    category: budget.category,
    amount: budget.amount,
    description: budget.description || ''
  }
  showEditModal.value = true
}

// 处理预算项拖拽排序
const handleSort = async (evt) => {
  const newOrders = budgets.value.map((budget, index) => ({
    id: budget.id,
    sort_order: index
  }))
  
  try {
    const response = await api.put('/api/update_budget_order', {
      orders: newOrders
    })
    if (response.data.code === 0) {
      showToast('排序更新成功', 'success')
    } else {
      showToast(response.data.message, 'error')
      await getBudgets() // 如果失败，重新获取列表恢复原始顺序
    }
  } catch (error) {
    showToast('排序更新失败', 'error')
    await getBudgets()
  }
}

// 计算进度条宽度百分比
const getProgressWidth = (budget) => {
  const used = budget.actual_expense || 0;
  const total = budget.amount;
  return (used / total) * 100;
}

// 根据预算使用情况计算进度条颜色
const getProgressColor = (budget) => {
  const used = budget.actual_expense || 0;
  const total = budget.amount;
  return used > total ? '#f56c6c' : '#67c23a'; // 超出预算为红色，否则为绿色
}

// 计算预算使用百分比
const getPercentage = (budget) => {
  const used = budget.actual_expense || 0;
  const total = budget.amount;
  return ((used / total) * 100).toFixed(2);
}

// 页面加载时获取预算数据
onMounted(() => {
  getBudgets()
})
</script>

<template>
  <div class="page-wrapper">
    <div class="page-container">
      <div class="budget-container">
        <Toast />
        
        <!-- 页面标题 -->
        <div class="page-header">
          <h2>月度预算管理</h2>
          <button class="add-btn" @click="showAddModal = true">
            <i class="icon">+</i>
            <span>添加预算</span>
          </button>
        </div>

        <!-- 总预算与实际预算卡片 -->
        <div class="budget-summary-card">
          <div class="summary-item total-budget">
            <div class="label">总预算</div>
            <div class="amount">¥{{ formatAmount(totalBudget) }}</div>
          </div>
          <div class="summary-item actual-expense">
            <div class="label">实际支出</div>
            <div class="amount" :style="{ color: actualExpenseColor }">¥{{ formatAmount(totalActualExpense) }}</div>
          </div>
        </div>

        <!-- 预算列表 -->
        <div class="budget-list">
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="budgets.length === 0" class="empty">暂无预算记录</div>
          <draggable 
            v-else
            v-model="budgets"
            class="budget-items"
            item-key="id"
            @end="handleSort"
            :ghost-class="'ghost'"
          >
            <template #item="{ element: budget }">
              <div class="budget-item">
                <div class="budget-info">
                  <div class="category">{{ getCategoryLabel(budget.category) }}</div>
                  <div class="amounts">
                    <span class="amount">预算: ¥{{ formatAmount(budget.amount) }}</span>
                    <span 
                      class="actual-amount" 
                      :style="{ color: getProgressColor(budget) }"
                    >
                      实际: ¥{{ formatAmount(budget.actual_expense || 0) }}
                    </span>
                    <span class="percentage">({{ getPercentage(budget) }}%)</span>
                  </div>
                  <div class="progress-bar">
                    <div 
                      class="progress" 
                      :style="{ width: getProgressWidth(budget) + '%', backgroundColor: getProgressColor(budget) }"
                    ></div>
                  </div>
                </div>
                <div class="budget-actions">
                  <button class="edit-btn" @click="openEditModal(budget)">编辑</button>
                  <button class="delete-btn" @click="handleDeleteBudget(budget.id)">删除</button>
                </div>
              </div>
            </template>
          </draggable>
        </div>

        <!-- 添加预算弹窗 -->
        <div v-if="showAddModal" class="modal">
          <div class="modal-content">
            <div class="modal-header">
              <h3>添加预算</h3>
              <button class="close-btn" @click="showAddModal = false">&times;</button>
            </div>
            <div class="form-content">
              <div class="form-item">
                <label>预算类型*</label>
                <select v-model="newBudget.category">
                  <option value="">请选择预算类型</option>
                  <option 
                    v-for="category in budgetCategories" 
                    :key="category.value" 
                    :value="category.value"
                  >
                    {{ category.label }}
                  </option>
                </select>
              </div>
              <div class="form-item">
                <label>预算金额*</label>
                <input 
                  type="number" 
                  v-model="newBudget.amount" 
                  placeholder="请输入预算金额"
                >
              </div>
              <div class="form-item">
                <label>备注说明</label>
                <textarea 
                  v-model="newBudget.description" 
                  placeholder="请输入备注信息"
                ></textarea>
              </div>
            </div>
            <div class="modal-footer">
              <button class="cancel-btn" @click="showAddModal = false">取消</button>
              <button class="confirm-btn" @click="handleAddBudget">确定</button>
            </div>
          </div>
        </div>

        <!-- 更新预算弹窗 -->
        <div v-if="showEditModal" class="modal">
          <div class="modal-content">
            <div class="modal-header">
              <h3>更新预算</h3>
              <button class="close-btn" @click="showEditModal = false">&times;</button>
            </div>
            <div class="form-content">
              <div class="form-item">
                <label>预算类型*</label>
                <select v-model="newBudget.category">
                  <option value="">请选择预算类型</option>
                  <option 
                    v-for="category in budgetCategories" 
                    :key="category.value" 
                    :value="category.value"
                  >
                    {{ category.label }}
                  </option>
                </select>
              </div>
              <div class="form-item">
                <label>预算金额*</label>
                <input 
                  type="number" 
                  v-model="newBudget.amount" 
                  placeholder="请输入预算金额"
                >
              </div>
              <div class="form-item">
                <label>备注说明</label>
                <textarea 
                  v-model="newBudget.description" 
                  placeholder="请输入备注信息"
                ></textarea>
              </div>
            </div>
            <div class="modal-footer">
              <button class="cancel-btn" @click="showEditModal = false">取消</button>
              <button class="confirm-btn" @click="handleUpdateBudget">确定</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page-wrapper {
  min-height: 100vh;
  overflow-x: hidden;
  background: #f5f7fa;
}

.page-container {
  display: flex;
  justify-content: center;
  min-height: 100vh;
}

.budget-container {
  width: 90%;
  max-width: 1300px;
  padding: 16px;
  box-sizing: border-box;
}

.page-header {
  background: white;
  border-radius: 8px;
  padding: 18px;
  margin-bottom: 18px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.add-btn {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-btn:hover {
  background: #66b1ff;
}

.add-btn .icon {
  font-size: 18px;
  margin-right: 4px;
}

.budget-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 20px 0;
}

.loading, .empty {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.budget-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.budget-item {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 12px;
  padding: 12px;
  transition: all 0.3s;
  cursor: move;
}

.budget-item:hover {
  background: #ecf5ff;
}

.budget-info {
  flex: 1;
  margin-right: 16px;
}

.category{
    color: #2c2c2c;
    font-size: 16px;
    font-weight: bold;
}

.amounts {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 4px;
}

.amount, .actual-amount, .percentage {
  font-size: 16px;
  color: #333;
}

.amount {
  color: #409eff;
  font-weight: bold;
}

.actual-amount {
  color: #67c23a;
  font-weight: bold;
}

.percentage {
  color: #909399;
}

.progress-bar {
  width: 100%;
  height: 10px;
  background: #ebeef5;
  border-radius: 5px;
  overflow: hidden;
  margin: 8px 0;
  position: relative;
}

.progress {
  height: 100%;
  transition: width 0.3s;
}

.budget-actions {
  display: flex;
  gap: 8px;
}

.edit-btn,
.delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 8px;
}

.edit-btn {
  background: #409eff;
  color: white;
}

.edit-btn:hover {
  background: #66b1ff;
}

.delete-btn {
  background: #f56c6c;
  color: white;
}

.delete-btn:hover {
  background: #f78989;
}

.budget-summary-card {
  display: flex;
  gap: 18px;
  margin-bottom: 18px;
}

.summary-item {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 18px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.summary-item .label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.summary-item .amount {
  font-size: 22px;
  font-weight: bold;
}

.summary-item.total-budget .amount {
  color: #409eff;
}

.summary-item.actual-expense .amount {
  color: #f56c6c;
}

.ghost {
  opacity: 1 !important;
  background: #e0f7fa;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 95%;
  max-width: 450px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 20px;
  color: #909399;
  cursor: pointer;
}

.form-content {
  padding: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.form-item input,
.form-item select,
.form-item textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.form-item textarea {
  min-height: 80px;
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
}

.confirm-btn {
  background: #409eff;
  color: white;
  border: none;
}
</style> 